from typing import Optional
from models.code_record import  CodeGenerationRecord
from repositories.base_repository import BaseRepository
from utils.database import Database

class CodeGenerationRecordRepository(BaseRepository[CodeGenerationRecord]):

    def __init__(self):
        pool = Database().pool
        super().__init__("code_generation_record", CodeGenerationRecord, pool)

    def get_latest_by_module_id(self, module_id: str) -> Optional[CodeGenerationRecord]:
        query = f"""
        SELECT * FROM {self.table_name} WHERE module_id = %s ORDER BY create_time DESC LIMIT 1
        """
        with Database() as db:
            result = db.query(query, (module_id,), fetch_one=True)
        return CodeGenerationRecord.from_dict(result) if result else None

    def insert(self, codeGenerationRecord: CodeGenerationRecord) -> int:
        query = f"""
               INSERT INTO {self.table_name} (
                   module_id, module_name, data_dictionary,
                   original_pseudo_code, normalized_intermediate_1,
                   normalized_intermediate_2, normalized_intermediate_3,
                   normalized_intermediate_4, normalized_intermediate_5,
                   normalized_intermediate_6, normalized_pseudo_code, 
                   c_code_status, c_code_error, generated_c_code, 
                   plugin_version, invocation_method
               ) VALUES (
                   %(module_id)s, %(module_name)s, %(data_dictionary)s,
                   %(original_pseudo_code)s, %(normalized_intermediate_1)s,
                   %(normalized_intermediate_2)s, %(normalized_intermediate_3)s,
                   %(normalized_intermediate_4)s, %(normalized_intermediate_5)s,
                   %(normalized_intermediate_6)s, %(normalized_pseudo_code)s, 
                   %(c_code_status)s, %(c_code_error)s, %(generated_c_code)s, 
                   %(plugin_version)s, %(invocation_method)s
               )
               """
        with Database() as db:
            db.dml(query, codeGenerationRecord.to_dict())
            result = db.query("SELECT LAST_INSERT_ID() as id", fetch_one=True)
            return result["id"] if result else 0

    def update(self, codeGenerationRecord: CodeGenerationRecord) -> bool:
        if not codeGenerationRecord.id:
            raise ValueError("codeGenerationRecord ID 不能为空")
        query = f"""
             UPDATE {self.table_name} SET
                module_id = %(module_id)s,
                module_name = %(module_name)s,
                data_dictionary = %(data_dictionary)s,
                original_pseudo_code = %(original_pseudo_code)s,
                normalized_intermediate_1 = %(normalized_intermediate_1)s,
                normalized_intermediate_2 = %(normalized_intermediate_2)s,
                normalized_intermediate_3 = %(normalized_intermediate_3)s,
                normalized_intermediate_4 = %(normalized_intermediate_4)s,
                normalized_intermediate_5 = %(normalized_intermediate_5)s,
                normalized_intermediate_6 = %(normalized_intermediate_6)s,
                normalized_pseudo_code = %(normalized_pseudo_code)s,
                c_code_status = %(c_code_status)s,
                c_code_error = %(c_code_error)s,
                generated_c_code = %(generated_c_code)s,
                plugin_version = %(plugin_version)s,
                invocation_method = %(invocation_method)s
            WHERE id = %(id)s
            """
        with Database() as db:
            affected_rows = db.dml(query, codeGenerationRecord.to_dict(include_id=True))
            return affected_rows > 0


if __name__ == "__main__":
    repo = CodeGenerationRecordRepository()

    """
    get_latest_by_module_id()
    """
    # module_id = 'ahbs-21bdhsw0'
    # record = repo.get_latest_by_module_id(module_id)
    # if record:
    #     print(f"找到记录: {record.__dict__}")
    # else:
    #     print(f"未找到module_id为{module_id}的记录")

    """
    insert()
    """
    codeGenerationRecord = CodeGenerationRecord()
    codeGenerationRecord.module_id = "MOD-001"
    codeGenerationRecord.module_name = "module_-001"
    codeGenerationRecord.original_pseudo_code = "oEGIN\n  IF user.age > 18 THEN\n    SET status = 'adult'\n  ENDIF\nEND"
    codeGenerationRecord.plugin_version = "1.0.0"
    record_id = repo.insert(codeGenerationRecord)
    print(record_id)

    """
    update()
    """
    # module_id = 'ahbs-21bdhsw0'
    # record = repo.get_latest_by_module_id(module_id)
    # record.c_code_status = 2
    # record.c_code_error = "error-occur"
    # repo.update(record)
    # record = repo.get_latest_by_module_id(module_id)
    # print(record.__dict__)